import Taro from '@tarojs/taro'
import app from '../../../../main.js'
let myJs = {
    getData: function() {
        this.state = {
            type: this.$router.params.type,
            relate_id: this.$router.params.relate_id,
            sender_type: '患者',
            receiver_type: '医生',
            data: '',
            value: '',
            sender_id: app.current.id,
            receiver_id: this.$router.params.receiver_id,
            mySelfId: '',
            otherId: '',
            url: app.apiUri + '/web/instant_chat_record/create',
            socketTask: null,
            messages: [],
            startTime: '',
            recordStatus: false,
            recorderManager: Taro.getRecorderManager()
        };
        return this.state;
    },
    // 初始化socket
    initSocket() {
        var me = this;
        Taro.connectSocket({
            url: app.wsUri+'?id='+ this.state.mySelfId,
            success: function () { 
                console.log('connect success')
            }
        }).then(task => {
            this.setState({
                socketTask: task
            })
            app.sockets.push(task);
            console.log('socketTask', task);
            console.log('sockets', app.sockets);
            task.onOpen(function () {
                console.log('onOpen')
            })
            task.onMessage(function (msg) {
                me.receiveMessage(msg);
            })
            task.onError(function () {
                console.log('onError')
            })
            task.onClose(function (e) {
                console.log('onClose: ', e)
                // me.initSocket();
            })
        })
    },
    // 接收消息
    receiveMessage(msg) {
        console.log('接收消息', msg);
        var me = this;
        var str = msg.data;
        str = str.replace('"{"', '{"');
        str = str.replace('}"}', '}}');
        var data = JSON.parse(str);
        if (!data.from) {
            return;
        }
        var id = data.from.split('-')[1];
        app.get('web/doctor/getById', {id: id}, function(res) {
            var messages = me.state.messages;
            var message = {
                type: data.type,
                data: data.data,
                isMyself: false,
                sender_id: app.current.id,
                sender_head_image: app.current.head_image,
                receiver_id: id,
                receiver_head_image: res.data.result.head_image
            };
            messages.push(message);
            me.setState({
                messages: messages
            })
        })
    },
    // 发送消息
    send(type) {
        var me = this;
        var params = {
            type: this.state.type,
            relate_id: this.state.relate_id,
            sender_type: this.state.sender_type,
            sender_id: this.state.sender_id,
            receiver_type: this.state.receiver_type,
            receiver_id: this.state.receiver_id, 
            content: {
                data: this.state.data,
                type: type,
            }
        }
        var data = {
            to: this.state.otherId,
            type: type,
            data: this.state.data,
            url: this.state.url,
            params: {
                params: JSON.stringify(params)
            }
        }

        console.log(JSON.stringify(data));
        this.state.socketTask.send({ 
            data: JSON.stringify(data), 
            success: function(res) {
                if (type == 'text') {
                    me.setState({
                        data: '',
                        value: ''
                    })
                }
                me.addMessage(data);
            }
        });
    },
    // 本地追加消息
    addMessage(data) {
        var me = this;
        var messages = me.state.messages;
        var message = {
            type: data.type,
            data: app.inArray(['audio', 'article', 'flow', 'flag', 'wz_illness_form'], data.type) ? JSON.parse(data.data) : data.data,
            isMyself: true,
            sender_id: app.current.id,
            sender_head_image: app.current.head_image,
            receiver_id: this.state.otherId.split('-')[1],
            receiver_head_image: ''
        };
        messages.push(message);
        me.setState({
            messages: messages
        })
    },
    // 从服务器获取聊天数据
    getMessages() {
        var me = this;
        var data = {
            offset: this.offset, 
            length: this.length,
            type: this.state.type,
            relate_id: this.state.relate_id
        }
        app.get('web/instant_chat_record/many', data, function(res) {
            Taro.stopPullDownRefresh(); // 停止下拉刷新

            var messages = [];
            var list = res.data.result.list;
            me.total = res.data.result.total;
            for (var i = 0; i < list.length; i++) {
                var item = list[i];
                var content = JSON.parse(item.content);
                var data = content.data;
                if (typeof data == 'string' && app.inArray(['audio', 'article', 'flow', 'flag', 'wz_illness_form'], content.type)) {
                    data = JSON.parse(data);
                }
                var message = {
                    type: content.type,
                    data: data,
                    is_play: false,
                    isMyself: item.sender_type == '患者' ? true : false,
                    sender_id: item.sender_id,
                    sender_head_image: item.sender_type == '患者' ? item.sender_head_image : item.receiver_head_image,
                    receiver_id: item.receiver_id,
                    receiver_head_image: item.receiver_type == '患者' ? item.sender_head_image : item.receiver_head_image 
                };
                messages.unshift(message);
            }

            messages = messages.concat(me.state.messages);

            me.setState({
                messages: messages
            });
        })
    },
    // 上传图片
    uploadImage() {
        var me = this;
        Taro.chooseImage({
            count: 1,
            sizeType: ['compressed'],
            sourceType: ['album', 'camera'],
            success (res) {
                const tempFilePaths = res.tempFilePaths
                Taro.uploadFile({
                    url: app.apiUri + '/admin/upload/image', //仅为示例，非真实的接口地址
                    filePath: tempFilePaths[0],
                    name: 'file',
                    formData: {
                        name: 'file'
                    },
                    success (rsp){
                        console.log(rsp);
                        var data = JSON.parse(rsp.data);
                        if (rsp.statusCode != 200 || data.status != 200) {
                            app.toastMessage('上传失败');
                            return;
                        }
                        me.setState({
                            data: data.result
                        }, () => {
                            me.send('image');
                        })
                    }
                })
            }
        })
    },
    // 上传视频
    uploadVideo() {
        var me = this;
        Taro.chooseVideo({
            sourceType: ['album','camera'],
            maxDuration: 60,
            camera: 'back',
            success(res) {
              console.log(res.tempFilePath)
              Taro.uploadFile({
                url: app.apiUri + '/admin/upload/image', //仅为示例，非真实的接口地址
                filePath: res.tempFilePath,
                name: 'file',
                formData: {
                    name: 'file'
                },
                success (rsp){
                    console.log(rsp)
                    var data = JSON.parse(rsp.data);
                    if (rsp.statusCode != 200 || data.status != 200) {
                        app.toastMessage('上传失败');
                        return;
                    }
                    me.setState({
                        data: data.result
                    }, () => {
                        me.send('video');
                    })
                }
            })
            }
        })
    },
    // 开始录音
    onTouchStart(e) {
        var me = this;
        Taro.getSetting({
            success(res) {
                if (!res.authSetting['scope.record']) {
                    Taro.authorize({
                        scope: 'scope.record',
                        success() {
                            
                        }
                    })
                }
            }
        })
        Taro.vibrateLong({});
        //记录开始录音时间
        me.setState({
            startTime: e.timeStamp
        })
        Taro.showLoading({
            title: '开始录音',
            mask: true
        })
        me.state.recorderManager.onStart(() => {
            console.log('recorder start')
        })
        me.state.recorderManager.start({
            duration: 600000,
            format: 'mp3'
        });
    },
    // 录音结束
    onTouchEnd(e) {
        var me = this;
        var endTime = e.timeStamp;
        var speakTime = endTime - me.state.startTime;
        //如果录音时间太短，提示
        if (speakTime < 350 ){
            Taro.showToast({
                title: '说话时间太短',
                icon: 'none',
            })
            this.state.recorderManager.stop();
        }else{ 
            Taro.hideLoading();
            Taro.showToast({
                title: '正在录音',
                icon: 'loading',
                duration: 1000,
                mask: true
            })
            this.state.recorderManager.onStop((res) => {
                console.log(res);
                //上传录制的音频
                Taro.uploadFile({
                    url: app.apiUri + '/admin/upload/image',
                    filePath: res.tempFilePath,
                    name: 'file',
                    formData: {
                        name: 'file'
                    },
                    success(rsp) {
                        var result = JSON.parse(rsp.data);
                        if (rsp.statusCode != 200 || result.status != 200) {             
                            app.toastMessage('录音失败');
                            return;
                        }
                        var data = {
                            time: Math.ceil(speakTime / 1000),
                            url: result.result
                        }
                        console.log(data);
                        me.setState({
                            data: JSON.stringify(data)
                        }, () => {
                            me.send('audio');
                        })
                    }
                })
            })
            //触发录音停止
            this.state.recorderManager.stop();
        }
    },
    // 回到页面底部
    toPageBottom() {
        var query = Taro.createSelectorQuery()
        query.select('#page_v').boundingClientRect()
        query.selectViewport().scrollOffset()
        query.exec(function(res){
            Taro.pageScrollTo({
                scrollTop: res[0].height,
                duration: 300
            })
        })
    },
    componentWillMount () {
        if(this.init) {
            this.init();
        }
    },
    navigateTo(url) {
        app.navigateTo(url);
    },
    handleChange(v) {
        this.setState({
            value: v,
            data: v
        })
    },
    handleTextareaChange(name, e) {
        var names = name.split('.');
        var n = names[0];
        var temp = this.state;
        for(var i = 0; i < names.length - 1; i++) {
            temp = temp[names[i]];
        }
        temp[names[i]] = e.target.value;
        this.setState({n: temp[names[i]]});
    },
    redirectTo(url) {
        app.redirectTo(url);
    },
    componentDidMount () {
        setTimeout(this.toPageBottom,500)
    },
    componentWillUnmount () {},
    componentDidHide () {}
}
export default myJs;
